package com.ec50n9.server.module.ebook

import com.ec50n9.server.module.common.Render
import com.ec50n9.server.module.common.Rendered
import com.ec50n9.server.module.common.renderTo
import com.ec50n9.server.module.ebookCategory.EbookCategory
import com.ec50n9.server.module.ebookCategory.EbookCategoryQueryRendered
import org.hibernate.annotations.GenericGenerator
import org.springframework.beans.BeanUtils
import javax.persistence.*
import javax.validation.constraints.NotBlank

@Entity
class Ebook(
    @Column(unique = true)
    var name: String,
    @ManyToOne
    var category: EbookCategory,
    var description: String? = null,
    var cover: String? = null,
    var docCount: Int = 0,
    var viewCount: Int = 0,
    var voteCount: Int = 0,

    @Id
    @GenericGenerator(name = "nanoid", strategy = "com.ec50n9.server.common.NanoIdGenerator")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "nanoid")
    var id: String? = null
) : Render<Ebook>()

/**
 * 详情渲染
 */
data class EbookDetailRendered(
    var id: String? = null,
    var name: String? = null,
    var category: EbookCategoryQueryRendered? = null,
    var description: String? = null,
    var cover: String? = null,
    var docCount: Int? = null,
    var viewCount: Int? = null,
    var voteCount: Int? = null,
) : Rendered<Ebook> {
    override fun renderFrom(from: Ebook) {
        BeanUtils.copyProperties(from, this)
        category = from.category.renderTo(EbookCategoryQueryRendered::class.java)
    }
}

/**
 * 列表渲染
 */
data class EbookListRendered(
    var id: String? = null,
    var name: String? = null,
    var categoryName: String? = null,
    var description: String? = null,
    var cover: String? = null,
    var docCount: Int? = null,
    var viewCount: Int? = null,
    var voteCount: Int? = null,
) : Rendered<Ebook> {
    override fun renderFrom(from: Ebook) {
        BeanUtils.copyProperties(from, this)
        categoryName = from.category.name
    }
}

/**
 * 创建表单
 */
data class EbookCreateForm(
    @field:NotBlank(message = "书名不能为空")
    var name: String? = null,

    @field:NotBlank(message = "分类名称不能为空")
    var categoryName: String? = null,

    var description: String? = null,
    var cover: String? = null,
    var docCount: Int? = null,
    var viewCount: Int? = null,
    var voteCount: Int? = null,
)

/**
 * 更新表单
 */
data class EbookUpdateForm(
    var name: String? = null,
    var categoryName: String? = null,
    var description: String? = null,
    var cover: String? = null,
    var docCount: Int? = null,
    var viewCount: Int? = null,
    var voteCount: Int? = null,
)
